<template>
	<div class="overflow-auto flex flex-col items-center">
		<m-svg-icon
			v-if="isMobileTerminal"
			name="close"
			fillClass="fill-zinc-900 dark:fill-zinc-200"
			class="w-3 h-3 p-0.5 m-1 ml-auto"
			@click="close"
		></m-svg-icon>

		<img :src="blob" ref="imageTarget" alt="" />

		<m-button
			:loading="loading"
			class="mt-4 w-[80%] xl:w-1/2"
			@click="onConfirmClick"
			>确定</m-button
		>
	</div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { isMobileTerminal } from '@/utils/flexible.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { getOssClient } from '@/utils/sts.js'
import { useStore } from 'vuex'
import { message } from '@/libs'
import { putProfile } from '@/api/sys/index.js'

const props = defineProps({
	blob: String,
})

const pcOptions = {
	aspectRatio: 1,
}

const mobileOptions = {
	viewMode: 1,
	dragMode: 'move',
	aspectRatio: 1,
	cropBoxMovable: false,
	cropBoxResizable: false,
}

const emits = defineEmits(['close'])
const close = () => {
	emits('close')
}

// 图片裁剪
const imageTarget = ref(null)
let cropper
onMounted(() => {
	cropper = new Cropper(
		imageTarget.value,
		isMobileTerminal.value ? mobileOptions : pcOptions
	)
})

const loading = ref(false)
const onConfirmClick = () => {
	loading.value = true

	// 拿到裁剪后的图片
	cropper.getCroppedCanvas().toBlob((blob) => {
		putObjectToOSS(blob)
	})
}

// 进行OSS的上传
const store = useStore()
let ossClient
const putObjectToOSS = async (file) => {
	if (!ossClient) {
		ossClient = await getOssClient()
	}

	try {
		const fileName = `${store.getters.userInfo.username}/${Date.now()}.${
			file.type.split('/')[1]
		}`
		const res = await ossClient.put(`images/${fileName}`, file)
		onChangeProfile(res.url)
	} catch (e) {
		message('error', e)
	}
}

// 上传新头像到服务器
const onChangeProfile = async (avatar) => {
	store.commit('user/setUserInfo', {
		...store.getters.userInfo,
		avatar,
	})

	await putProfile(store.getters.userInfo)
	message('success', '修改成功')
	loading.value = false
	close()
}
</script>

<style scoped lang="scss"></style>
